﻿using System;
using System.IO;

namespace DAL.File
{
    public class FileAccess: IFileAccess
    {
        #region IFileAccess Members

        public string SharedRoot { get { return AppDomain.CurrentDomain.BaseDirectory + @"\Profiles\"; } }

        public byte[] ReadFile(string path)
        {
            try { return System.IO.File.ReadAllBytes(path); }
            catch { return null; }
        }

        public void WriteFile(string path, byte[] data)
        {
            System.IO.File.WriteAllBytes(ProvidePath(path), data);
        }

        public void DeleteFile(string path)
        {
            try
            {
                if (System.IO.File.Exists(path))
                    System.IO.File.Delete(path);                
            } catch
            {
                
            }
        }

        public string[] GetFolderContents(string path, bool onlyDirs)
        {
            return !Directory.Exists(path) ? new string[0] : onlyDirs ? Directory.GetDirectories(path) : Directory.GetFileSystemEntries(path);
        }

        #endregion

        #region File system watcher

        private FileSystemWatcher fsWatcher;
        public event EventHandler<FileChangedEvent> FileChangedEvent;

        public void SetFolderWatcher(string path)
        {
            if(fsWatcher != null)
                fsWatcher.Dispose();

            Action<string> changed = fn =>
            {
                if (FileChangedEvent != null)
                    FileChangedEvent(this, new FileChangedEvent(fn));
            };
                
            fsWatcher = new FileSystemWatcher(ProvidePath(path)) { IncludeSubdirectories = true, EnableRaisingEvents = true };
            fsWatcher.Created += (sender, args) => changed(args.FullPath);
            //FsWatcher.Deleted += (sender, args) => changed(args.FullPath);
            //FsWatcher.Changed += (sender, args) => changed(args.FullPath);
            //FsWatcher.Renamed += (sender, args) => changed(args.FullPath);
        }

        public void Dispose()
        {
            if(fsWatcher != null)
                fsWatcher.Dispose();
        }

        #endregion

        private static string ProvidePath(string filename)
        {
            filename = Path.GetFullPath(filename);
            var di = new DirectoryInfo(Path.GetDirectoryName(filename));
            di.Create();
            return filename;
        }
    }
}
